import sys

import cv2
import numpy as np
from ctypes import windll
import win32gui
import win32ui


def capture_win_alt(window_name: str):
    windll.user32.SetProcessDPIAware()
    hwnd = win32gui.FindWindow(None, window_name)
    if not hwnd:
        print(f"无法找到名称为{window_name}的窗口")
        return None
    left, top, right, bottom = win32gui.GetClientRect(hwnd)
    w = right - left
    h = bottom - top
    hwnd_dc = win32gui.GetWindowDC(hwnd)
    mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)
    save_dc = mfc_dc.CreateCompatibleDC()
    bitmap = win32ui.CreateBitmap()
    bitmap.CreateCompatibleBitmap(mfc_dc, w, h)
    save_dc.SelectObject(bitmap)
    result = windll.user32.PrintWindow(hwnd, save_dc.GetSafeHdc(), 3)
    if not result:
        win32gui.DeleteObject(bitmap.GetHandle())
        save_dc.DeleteDC()
        mfc_dc.DeleteDC()
        win32gui.ReleaseDC(hwnd, hwnd_dc)
        return None
    bmpinfo = bitmap.GetInfo()
    bmpstr = bitmap.GetBitmapBits(True)
    img = np.frombuffer(bmpstr, dtype=np.uint8).reshape((bmpinfo["bmHeight"], bmpinfo["bmWidth"], 4))
    img = np.ascontiguousarray(img)[..., :-1]
    return img


def main():
    WINDOW_NAME = "C:\Windows\system32\cmd.exe"
    while True:
        if cv2.waitKey(100) == 27:
            print("程序结束！")
            cv2.destroyWindow('clc')
            break
        screenshot = capture_win_alt(WINDOW_NAME)
        if screenshot is None:
            continue
        else:
            cv2.imshow('clc', screenshot)

    sys.exit(0)

if __name__ == '__main__':
    main()
